package com.ruoyi.cms.controller.my;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.ruoyi.cms.domain.CmsArticle;
import com.ruoyi.cms.domain.CmsOrder;
import com.ruoyi.cms.domain.CmsOrderMessage;
import com.ruoyi.cms.service.ICmsArticleService;
import com.ruoyi.cms.service.ICmsOrderMessageService;
import com.ruoyi.cms.service.ICmsOrderService;
import com.ruoyi.common.config.AlipayConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/cmsNotify")
public class CmsNotifyController extends BaseController {

    @Autowired
    ICmsOrderService cmsOrderService;
    @Autowired
    ICmsArticleService cmsArticleService;

    @Autowired
    ICmsOrderMessageService cmsOrderMessageService;

    @Autowired
    AlipayConfig alipayConfig;

    @RequestMapping("/zhanshang")
    public int zhangshang(String data){
        JSONObject jsonObject = JSONObject.parseObject(data);
        int amount = jsonObject.getInteger("money");
        List<CmsOrder> orders = cmsOrderService.selectListByUserIdAndDate( 120, amount);
        if(CollectionUtils.isNotEmpty(orders)){
            for(CmsOrder tempOrder : orders){
                tempOrder.setOrderStatus(2);
                cmsOrderService.updateCmsOrder(tempOrder);

                CmsArticle cmsArticle = cmsArticleService.selectCmsArticleById(tempOrder.getArticleId());

                CmsOrderMessage cmsOrderMessage = new CmsOrderMessage();
                cmsOrderMessage.setUserId(tempOrder.getUserId());
                cmsOrderMessage.setTitle(cmsArticle.getTitle());
                cmsOrderMessage.setShareUrl(cmsArticle.getShareUrl());
                cmsOrderMessage.setShareCode(cmsArticle.getShareCode());
                cmsOrderMessage.setContent("来之于网络分享的链接:"+cmsArticle.getShareUrl()+",提取码：:"+cmsArticle.getShareCode());
                cmsOrderMessage.setCreateTime(new Date());
                cmsOrderMessageService.insertCmsOrderMessage(cmsOrderMessage);
            }

        }
        System.out.println("zhangshang:"+data);
        return 200;
    }

    @PostMapping("/alipay")
    public String alipay(HttpServletRequest request) {
        try {
            // 1. 转换请求参数为Map
            Map<String, String> params = convertRequestParams(request);

            // 2. 验证签名（核心步骤）
            boolean signVerified = AlipaySignature.rsaCheckV1(
                    params,
                    alipayConfig.getAlipayPublicKey(), // 支付宝公钥
                    alipayConfig.getCharset(),
                    alipayConfig.getSignType()
            );

            if (!signVerified) {
                return "failure"; // 签名验证失败
            }

            // 3. 处理业务逻辑
            String tradeStatus = params.get("trade_status");
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
//                String outTradeNo = params.get("out_trade_no");
//                String tradeNo = params.get("trade_no");
//                BigDecimal totalAmount = new BigDecimal(params.get("total_amount"));
                String orderId = params.get("orderId");
                String userId = params.get("userId");
                String articleTitle  = params.get("articleTitle");
                String shareUrl = params.get("shareUrl");
                String shareCode = params.get("shareCode");
                CmsOrder order = cmsOrderService.selectCmsOrderById(new Long(orderId));
                if(order != null){
                    order.setOrderStatus(2);
                    cmsOrderService.updateCmsOrder(order);

                    CmsOrderMessage cmsOrderMessage = new CmsOrderMessage();
                    cmsOrderMessage.setUserId(new Long(userId));
                    cmsOrderMessage.setTitle(articleTitle);
                    cmsOrderMessage.setShareUrl(shareUrl);
                    cmsOrderMessage.setShareCode(shareCode);
                    cmsOrderMessage.setContent("来之于网络分享的链接:"+shareCode+",提取码：:"+shareCode);
                    cmsOrderMessage.setCreateTime(new Date());
                    cmsOrderMessageService.insertCmsOrderMessage(cmsOrderMessage);
                    return "success";
                }else{
                    return "failure";
                }

            }

            return "failure";
        } catch (AlipayApiException e) {
            return "failure";
        }
    }

    private Map<String, String> convertRequestParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = String.join(",", values);
            params.put(name, valueStr);
        }
        System.out.println(JSON.toJSONString(params));
        return params;
    }

    @RequestMapping("/mobileMsg")
    public int mobileMsg(@RequestBody JSONObject data){
        try{
            System.out.println(data);
//            data = JSON.parseObject("{\"product\":\"huanyoushequ\",\"data\":\"{\\\"channel\\\":\\\"alipay\\\",\\\"uid\\\":\\\"10494\\\",\\\"title\\\":你已成功收款1.00元.\\\",\\\"msg\\\":\\\"已开通笔笔转入余额宝 做生意收钱提现免费>>\\\",\\\"time\\\":\\\"2025-05-14 16:31:26\\\",\\\"divice\\\":\\\"\\\"}\",\"time\":\"1747211486481\"}\n");
            String product = data.getString("product");
            if("huanyoushequ".equals(product)){
                JSONObject tempData = data.getJSONObject("data");
                String title = tempData.getString("title");

                Pattern pattern = Pattern.compile("\\d+\\.\\d{2}");
                Matcher matcher = pattern.matcher(title);
                if(matcher.find()){
                    String amountStr = matcher.group();
                    try{
                        int amount = new BigDecimal(amountStr).intValue();
                        List<CmsOrder> orders = cmsOrderService.selectListByUserIdAndDate( 120, amount);
                        if(CollectionUtils.isNotEmpty(orders)){
                            for(CmsOrder tempOrder : orders){
                                tempOrder.setOrderStatus(2);
                                cmsOrderService.updateCmsOrder(tempOrder);

                                CmsArticle cmsArticle = cmsArticleService.selectCmsArticleById(tempOrder.getArticleId());

                                CmsOrderMessage cmsOrderMessage = new CmsOrderMessage();
                                cmsOrderMessage.setUserId(tempOrder.getUserId());
                                cmsOrderMessage.setTitle(cmsArticle.getTitle());
                                cmsOrderMessage.setShareUrl(cmsArticle.getShareUrl());
                                cmsOrderMessage.setShareCode(cmsArticle.getShareCode());
                                cmsOrderMessage.setContent("来之于网络分享的链接:"+cmsArticle.getShareUrl()+",提取码：:"+cmsArticle.getShareCode());
                                cmsOrderMessage.setCreateTime(new Date());
                                cmsOrderMessageService.insertCmsOrderMessage(cmsOrderMessage);
                            }

                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
            return 200;
        }catch (Exception e){
            e.printStackTrace();
        }
        return 200;

    }


}
